import mqtt from 'mqtt'
const mqttUrl = "/"

export default {
  connection: (row) => {
    return {
      host: row.ipAddress,
      port: row.port,
      connectTimeout: 4000, // 超时时间
      reconnectPeriod: 4000, // 重连时间间隔
      protocol: 'ws',
    }
  },
  client: {
    connected: false,
  },
  Uint8ArrayToString: function (fileData) {
    var decoder = new TextDecoder('utf-8');
    return decoder.decode(fileData);
  },
  // 创建连接
  createConnection: function (row) {
    return new Promise((r) => {
      const { host, port, ...options } = this.connection(row)
      const connectUrl = `ws://${host}:${port}/mqtt`
      this.client = mqtt.connect(connectUrl, options)
      this.client.on('connect', () => {
        console.log('Connection succeeded!')
        for (let item of row.topicList) {
          this.client.subscribe(item.topic, (err) => {
            if (!err) {
              console.log("订阅成功");
            }
          });
        }
      })
      this.client.on('error', error => {
        console.log('Connection failed', error)
      })
      r(this.client)
    })
  },
  sendMessage: function (topic, data) {
    this.client.publish(topic, JSON.stringify(data));
  }
}